﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Threading;
using System.Reflection.Emit;
using System.Reflection;
using System.Data;
using System.Data.Odbc;
using System.Xml;

namespace fap
{
    class WPF动画类
    {

        /// <summary>
        /// 同时旋转和缩放的动画
        /// </summary>
        /// <param name="element"></param>
        /// <param name="Sizefrom"></param>
        /// <param name="Sizeto"></param>
        /// <param name="anglefrom"></param>
        /// <param name="angleto"></param>
        /// <param name="time"></param>
        /// <param name="Power"></param>
        /// <param name="completed"></param>
        public static void ScaleEasingAnimationShow(UIElement element, double Sizefrom, double Sizeto, int anglefrom, int angleto, double 秒, int Power/*, EventHandler completed*/)
        {
            TimeSpan timeSpan = new TimeSpan(0, 0, 0, 0, (int)(秒 * 1000));

            RotateTransform angle = new RotateTransform();  //旋转
            ScaleTransform scale = new ScaleTransform();   //缩放

            TransformGroup group = new TransformGroup();
            group.Children.Add(scale);
            group.Children.Add(angle);

            element.RenderTransform = group;
            //定义圆心位置
            //元素开始的位置是从new Point（0，0）到new Point（1，1），
            //左上角为（0，0）、右下角为（1，1），控件大小范围为（1，0） 1为控件本身大小，0 为控件缩放完，不显示。
            element.RenderTransformOrigin = new System.Windows.Point(0.5, 0.5);
            //载入动画，淡入淡出等。
            EasingFunctionBase easeFunction = new PowerEase()
            {
                EasingMode = EasingMode.EaseInOut,
                Power = Power
            };
            //缩放动画
            DoubleAnimation scaleAnimation = new DoubleAnimation()
            {
                From = Sizefrom,                                   //起始值
                To = Sizeto,                                     //结束值
                EasingFunction = easeFunction,                    //缓动函数
                Duration = timeSpan,  //动画播放时间


            };
            //旋转动画
            DoubleAnimation angleAnimation = new DoubleAnimation()
            {
                From = anglefrom,                                   //起始值
                To = angleto,                                     //结束值
                EasingFunction = easeFunction,              //缓动函数
                FillBehavior = FillBehavior.HoldEnd,
                Duration = timeSpan,  //动画播放时间

            };

            //angleAnimation.Completed += completed;
            //scaleAnimation.Completed += new EventHandler(scaleAnimation_Completed);
            //  AnimationClock clock = scaleAnimation.CreateClock();
            scale.BeginAnimation(ScaleTransform.ScaleXProperty, scaleAnimation);
            scale.BeginAnimation(ScaleTransform.ScaleYProperty, scaleAnimation);
            angle.BeginAnimation(RotateTransform.AngleProperty, angleAnimation);

        }

        /// <summary>
        /// 控件绕中心缩放动画
        /// </summary>
        /// <param name="element">控件名</param>
        /// <param name="Sizefrom">开始大小</param>
        /// <param name="Sizeto">结束大小</param>
        /// <param name="power">过渡强度</param>
        /// <param name="time">持续时间，例如3秒： TimeSpan(0,0,3) </param>
        public static void ScaleEasingAnimationShow(UIElement element, double Sizefrom, double Sizeto, int power, double 秒)
        {
            TimeSpan timeSpan = new TimeSpan(0, 0, 0, 0, (int)(秒 * 1000));
            ScaleTransform scale = new ScaleTransform();  //旋转
            element.RenderTransform = scale;
            //定义圆心位置
            element.RenderTransformOrigin = new System.Windows.Point(0.5, 0.5);
            //定义过渡动画,power为过度的强度
            EasingFunctionBase Function = new PowerEase()
            {
                EasingMode = EasingMode.EaseInOut,
                Power = power
            };

            DoubleAnimation scaleAnimation = new DoubleAnimation()
            {
                From = Sizefrom,                                   //起始值
                To = Sizeto,                                     //结束值
                FillBehavior = FillBehavior.HoldEnd,
                Duration = timeSpan,                                 //动画播放时间
            };
            scale.BeginAnimation(ScaleTransform.ScaleXProperty, scaleAnimation);
            scale.BeginAnimation(ScaleTransform.ScaleYProperty, scaleAnimation);
        }

        ///deskPoint: 控件要移动到的位置 , ell :你要移动的空间 , space : 设置移动的时间片（关系到控件移动的速度）
        public static void moveTo(double X, double Y, Control ell, double time)


        {
            Point curPoint = new Point();
            curPoint.X = Canvas.GetLeft(ell);
            curPoint.Y = Canvas.GetTop(ell);


            Storyboard storyboard = new Storyboard();   //创建Storyboard对象

            double lxspeed = time, lyspeed = time; //设置X方向 / Y方向 移动时间片

            //创建X轴方向动画 

            DoubleAnimation doubleAnimation = new DoubleAnimation(
              Canvas.GetLeft(ell),
              X,
              new Duration(TimeSpan.FromMilliseconds(lxspeed))
            );
            Storyboard.SetTarget(doubleAnimation, ell);
            Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath("(Canvas.Left)"));
            storyboard.Children.Add(doubleAnimation);


            //创建Y轴方向动画 


            doubleAnimation = new DoubleAnimation(
              Canvas.GetTop(ell),
              Y,
              new Duration(TimeSpan.FromMilliseconds(lyspeed))
            );
            Storyboard.SetTarget(doubleAnimation, ell);
            Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath("(Canvas.Top)"));
            storyboard.Children.Add(doubleAnimation);



            //动画播放 
            storyboard.Begin();

        }

        public static void moveTo(double X, double Y, UIElement ell, double time)


        {
            Point curPoint = new Point();
            curPoint.X = Canvas.GetLeft(ell);
            curPoint.Y = Canvas.GetTop(ell);


            Storyboard storyboard = new Storyboard();   //创建Storyboard对象

            double lxspeed = time, lyspeed = time; //设置X方向 / Y方向 移动时间片

            //创建X轴方向动画 

            DoubleAnimation doubleAnimation = new DoubleAnimation(
              Canvas.GetLeft(ell),
              X,
              new Duration(TimeSpan.FromMilliseconds(lxspeed))
            );
            Storyboard.SetTarget(doubleAnimation, ell);
            Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath("(Canvas.Left)"));
            storyboard.Children.Add(doubleAnimation);


            //创建Y轴方向动画 


            doubleAnimation = new DoubleAnimation(
              Canvas.GetTop(ell),
              Y,
              new Duration(TimeSpan.FromMilliseconds(lyspeed))
            );
            Storyboard.SetTarget(doubleAnimation, ell);
            Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath("(Canvas.Top)"));
            storyboard.Children.Add(doubleAnimation);



            //动画播放 
            storyboard.Begin();
        }


        public static void 旋转动画(Control 控件, double 初始角度, double 最终角度, double 变化时间)
        {
            Storyboard sto = new Storyboard();
            RotateTransform rtf = new RotateTransform();
            控件.RenderTransform = rtf;
            //添加一个旋转中心
            控件.RenderTransformOrigin = new Point(0.5, 0.5);  //0.5表示百分数


            DoubleAnimation da = new DoubleAnimation(初始角度, 最终角度, new Duration(TimeSpan.FromSeconds(变化时间)));
            Storyboard.SetTarget(da, 控件);
            Storyboard.SetTargetProperty(da, new PropertyPath("RenderTransform.Angle"));
            sto.Children.Add(da);
            sto.Begin();
        }

        public static void 渐变消失(UIElement 控件, double 初始, double 结束, double 变化时间)
        {
            Storyboard st = new Storyboard();
            DoubleAnimation da = new DoubleAnimation();
            da.From = 初始;
            da.To = 结束;
            da.Duration = new Duration(TimeSpan.FromSeconds(变化时间));
            Storyboard.SetTarget(da, 控件);
            Storyboard.SetTargetProperty(da, new PropertyPath("Opacity"));
            st.Children.Add(da);
            st.Begin();
        }
        public static void 渐变颜色(UIElement 控件, Color 初始, Color 结束, double 变化时间)
        {
            Storyboard st = new Storyboard();
            ColorAnimation color = new ColorAnimation(初始, 结束, new Duration(TimeSpan.FromSeconds(变化时间)));
            Storyboard.SetTarget(color, 控件);
            Storyboard.SetTargetProperty(color, new PropertyPath("(Border.Background).(SolidColorBrush.Color)"));
            st.Children.Add(color);
            st.Begin();
        }
        public static void 移动(UIElement 控件, double 初始x, double 初始y, double 最终x, double 最终y, double 变化时间)
        {
            Storyboard st = new Storyboard();

            DoubleAnimation dos = new DoubleAnimation(初始x, 最终x, new Duration(TimeSpan.FromSeconds(变化时间)));
            Storyboard.SetTarget(dos, 控件);
            Storyboard.SetTargetProperty(dos, new PropertyPath("(Canvas.Left)"));
            st.Children.Add(dos);
            DoubleAnimation dos2 = new DoubleAnimation(初始y, 最终y, new Duration(TimeSpan.FromSeconds(变化时间)));
            Storyboard.SetTarget(dos2, 控件);
            Storyboard.SetTargetProperty(dos2, new PropertyPath("(Canvas.Top)"));
            st.Children.Add(dos2);
            //st.Completed += St_Completed;
            st.Begin();
        }
    }
    class WPF相应类
    {
        /// <summary>  
        /// 获得指定元素的所有子元素  
        /// </summary>  
        /// <typeparam name="T"></typeparam>  
        /// <param name="obj"></param>  
        /// <returns></returns>  
        public static List<T> GetChildObjects<T>(DependencyObject obj) where T : FrameworkElement
        {
            DependencyObject child = null;
            List<T> childList = new List<T>();

            for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++)
            {
                child = VisualTreeHelper.GetChild(obj, i);

                if (child is T)
                {
                    childList.Add((T)child);
                }
                childList.AddRange(GetChildObjects<T>(child));
            }
            return childList;
        }


        /// <summary>
        /// 控件绕中心缩放动画
        /// </summary>
        /// <param name="element">控件名</param>
        /// <param name="Sizefrom">开始大小</param>
        /// <param name="Sizeto">结束大小</param>
        /// <param name="power">过渡强度</param>
        /// <param name="time">持续时间，例如3秒： TimeSpan(0,0,3) </param>
        public static void ScaleEasingAnimationShow(UIElement element, double Sizefrom, double Sizeto, int power, TimeSpan time)
        {
            ScaleTransform scale = new ScaleTransform();  //旋转
            element.RenderTransform = scale;
            //定义圆心位置
            element.RenderTransformOrigin = new System.Windows.Point(0.5, 0.5);
            //定义过渡动画,power为过度的强度
            EasingFunctionBase Function = new PowerEase()
            {
                EasingMode = EasingMode.EaseInOut,
                Power = power
            };

            DoubleAnimation scaleAnimation = new DoubleAnimation()
            {
                From = Sizefrom,                                   //起始值
                To = Sizeto,                                     //结束值
                FillBehavior = FillBehavior.HoldEnd,
                Duration = time,                                 //动画播放时间
            };
            scale.BeginAnimation(ScaleTransform.ScaleXProperty, scaleAnimation);
            scale.BeginAnimation(ScaleTransform.ScaleYProperty, scaleAnimation);
        }

        ///deskPoint: 控件要移动到的位置 , ell :你要移动的空间 , space : 设置移动的时间片（关系到控件移动的速度）
        public static void moveTo(double X, double Y, Control ell, double time)


        {
            Point curPoint = new Point();
            curPoint.X = Canvas.GetLeft(ell);
            curPoint.Y = Canvas.GetTop(ell);


            Storyboard storyboard = new Storyboard();   //创建Storyboard对象

            double lxspeed = time, lyspeed = time; //设置X方向 / Y方向 移动时间片

            //创建X轴方向动画 

            DoubleAnimation doubleAnimation = new DoubleAnimation(
              Canvas.GetLeft(ell),
              X,
              new Duration(TimeSpan.FromMilliseconds(lxspeed))
            );
            Storyboard.SetTarget(doubleAnimation, ell);
            Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath("(Canvas.Left)"));
            storyboard.Children.Add(doubleAnimation);


            //创建Y轴方向动画 


            doubleAnimation = new DoubleAnimation(
              Canvas.GetTop(ell),
              Y,
              new Duration(TimeSpan.FromMilliseconds(lyspeed))
            );
            Storyboard.SetTarget(doubleAnimation, ell);
            Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath("(Canvas.Top)"));
            storyboard.Children.Add(doubleAnimation);



            //动画播放 
            storyboard.Begin();

        }

        public static void moveTo(double X, double Y, UIElement ell, double time)


        {
            Point curPoint = new Point();
            curPoint.X = Canvas.GetLeft(ell);
            curPoint.Y = Canvas.GetTop(ell);


            Storyboard storyboard = new Storyboard();   //创建Storyboard对象

            double lxspeed = time, lyspeed = time; //设置X方向 / Y方向 移动时间片

            //创建X轴方向动画 

            DoubleAnimation doubleAnimation = new DoubleAnimation(
              Canvas.GetLeft(ell),
              X,
              new Duration(TimeSpan.FromMilliseconds(lxspeed))
            );
            Storyboard.SetTarget(doubleAnimation, ell);
            Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath("(Canvas.Left)"));
            storyboard.Children.Add(doubleAnimation);


            //创建Y轴方向动画 


            doubleAnimation = new DoubleAnimation(
              Canvas.GetTop(ell),
              Y,
              new Duration(TimeSpan.FromMilliseconds(lyspeed))
            );
            Storyboard.SetTarget(doubleAnimation, ell);
            Storyboard.SetTargetProperty(doubleAnimation, new PropertyPath("(Canvas.Top)"));
            storyboard.Children.Add(doubleAnimation);



            //动画播放 
            storyboard.Begin();
        }


        public void 委托()
        {
            //Dispatcher.Invoke((Action)(() =>
            //{

            //}));
        }

        static int x = 0;
        public static void 写入rich(RichTextBox richTextBox, string str)
        {
            try
            {

                if (x > 100)
                {
                    richTextBox.Document.Blocks.Clear();
                    x = 0;
                }

                //richTextBox.Document.Blocks.Clear();
                str = "\n" + DateTime.Now.ToString("HH:mm:ss") + "  " + str;
                richTextBox.AppendText(str);
                richTextBox.ScrollToEnd();
                x++;




            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }


        #region  wpf客户端 导出DataGrid数据到Excel

        /// <summary>
        /// CSV格式化
        /// </summary>
        /// <param name="data">数据</param>
        /// <returns>格式化数据</returns>
        private static string FormatCsvField(string data)
        {
            return String.Format("\"{0}\"", data.Replace("\"", "\"\"\"").Replace("\n", "").Replace("\r", ""));
        }



        /// <summary>
        /// 导出DataGrid数据到Excel
        /// </summary>
        /// <param name="withHeaders">是否需要表头</param>
        /// <param name="grid">DataGrid</param>
        /// <param name="dataBind"></param>
        /// <returns>Excel内容字符串</returns>
        public static string ExportDataGrid(System.Windows.Controls.DataGrid grid)
        {
            try
            {
                var strBuilder = new System.Text.StringBuilder();
                var source = (grid.ItemsSource as System.Collections.IList);
                if (source == null) return "";
                var headers = new List<string>();
                List<string> bt = new List<string>();

                foreach (var hr in grid.Columns)
                {
                    //   DataGridTextColumn textcol = hr. as DataGridTextColumn;
                    headers.Add(hr.Header.ToString());
                    if (hr is DataGridTextColumn)//列绑定数据
                    {
                        DataGridTextColumn textcol = hr as DataGridTextColumn;
                        if (textcol != null)
                            bt.Add((textcol.Binding as Binding).Path.Path.ToString());        //获取绑定源      

                    }
                    else if (hr is DataGridTemplateColumn)
                    {
                        if (hr.Header.Equals("操作"))
                            bt.Add("Id");
                    }
                    else
                    {

                    }
                }
                strBuilder.Append(String.Join(",", headers.ToArray())).Append("\r\n");
                foreach (var data in source)
                {
                    var csvRow = new List<string>();
                    foreach (var ab in bt)
                    {
                        string s = ReflectionUtil.GetProperty(data, ab).ToString();
                        if (s != null)
                        {
                            csvRow.Add(FormatCsvField(s));
                        }
                        else
                        {
                            csvRow.Add("\t");
                        }
                    }
                    strBuilder.Append(String.Join(",", csvRow.ToArray())).Append("\r\n");
                    // strBuilder.Append(String.Join(",", csvRow.ToArray())).Append("\t");
                }
                return strBuilder.ToString();
            }
            catch (Exception ex)
            {

                return "";
            }
        }
        /// <summary>
        /// 导出DataGrid数据到Excel为CVS文件
        /// 使用utf8编码 中文是乱码 改用Unicode编码
        /// 
        /// </summary>
        /// <param name="withHeaders">是否带列头</param>
        /// <param name="grid">DataGrid</param>
        public static void ExportDataGridSaveAs(bool withHeaders, System.Windows.Controls.DataGrid grid)
        {
            try
            {
                string data = ExportDataGrid(grid);
                var sfd = new Microsoft.Win32.SaveFileDialog
                {
                    DefaultExt = "csv",
                    Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*",
                    FilterIndex = 1
                };
                if (sfd.ShowDialog() == true)
                {
                    using (Stream stream = sfd.OpenFile())
                    {
                        using (var writer = new StreamWriter(stream, System.Text.Encoding.Unicode))
                        {
                            data = data.Replace(",", "\t");
                            writer.Write(data);
                            writer.Close();
                        }
                        stream.Close();
                    }
                }
                MessageBox.Show("导出成功！");
            }
            catch (Exception ex)
            {

            }
        }

        #endregion 导出DataGrid数据到Excel



        /// <summary>
        /// 利用反射将Datatable转换为List<T>对象
        /// </summary>
        /// <typeparam name="T">集合</typeparam>
        /// <param name="dt"> datatable对象</param>
        /// <returns></returns>
        public static List<T> DataTableToList<T>(DataTable dt) where T : new()
        {

            //定义集合
            List<T> ts = new List<T>();

            //遍历dataTable中的数据行
            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                //获得此模型的公共属性
                PropertyInfo[] propertys = t.GetType().GetProperties();

                //遍历该对象的所有属性
                foreach (PropertyInfo pi in propertys)
                {

                    string tempName = pi.Name;

                    if (!dt.Columns.Contains(tempName)) continue;   //检查datatable是否包含此列(列名==对象的属性名)    
                    object value = dr[tempName];      //取值
                    if (value == DBNull.Value) continue;  //如果非空，则赋给对象的属性
                    pi.SetValue(t, value, null);
                }
                //对象添加到泛型集合中
                ts.Add(t);
            }
            return ts;

        }


    }
    /// <summary>
    /// 反射
    /// </summary>
    public class ReflectionUtil
    {
        public static object GetProperty(object obj, string propertyName)
        {
            PropertyInfo info = obj.GetType().GetProperty(propertyName);
            if (info == null && propertyName.Split('.').Count() > 0)
            {
                object o = ReflectionUtil.GetProperty(obj, propertyName.Split('.')[0]);
                int index = propertyName.IndexOf('.');
                string end = propertyName.Substring(index + 1, propertyName.Length - index - 1);
                return ReflectionUtil.GetProperty(o, end);
            }
            object result = null;
            try
            {
                result = info.GetValue(obj, null);
            }
            catch (TargetException)
            {
                return "";
            }
            return result == null ? "" : result;
        }
    }


    public class datatable转换
    {
        //DataTable转换成XML
        static public string ConvertDataTableToXML(DataTable xmlDS)
        {
            MemoryStream stream = null;
            XmlTextWriter writer = null;
            try
            {
                stream = new MemoryStream();
                writer = new XmlTextWriter(stream, Encoding.UTF8);
                xmlDS.WriteXml(writer);
                int count = (int)stream.Length;
                byte[] arr = new byte[count];
                stream.Seek(0, SeekOrigin.Begin);
                stream.Read(arr, 0, count);
                UTF8Encoding utf = new UTF8Encoding();

                return utf.GetString(arr).Trim();
            }
            catch
            {
                return String.Empty;
            }
            finally
            {
                if (writer != null) writer.Close();
            }
        }

        //XML转datatable
        static public DataSet ConvertXMLToDataSet(string xmlData)
        {
            StringReader stream = null;
            XmlTextReader reader = null;
            try
            {
                DataSet xmlDS = new DataSet();
                stream = new StringReader(xmlData);
                reader = new XmlTextReader(stream);
                xmlDS.ReadXml(reader);

                return xmlDS;
            }
            catch (Exception ex)
            {
                string strTest = ex.Message;
                return null;
            }
            finally
            {
                if (reader != null)
                    reader.Close();
            }
        }



        public static DataSet ConvertXMLToDataSet1(string xmlData)
        {
            xmlData = "<" + xmlData.Substring(xmlData.IndexOf('<') + 1);
            StringReader stream = null;
            XmlTextReader reader = null;
            try
            {
                DataSet xmlDS = new DataSet();
                stream = new StringReader(xmlData);
                //从stream装载到XmlTextReader
                reader = new XmlTextReader(stream);
                xmlDS.ReadXml(reader);
                return xmlDS;
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (reader != null) reader.Close();
            }




        }



    }

    class WPFgrid类
    {
     
        public static System.Windows.Controls.DockPanel grid动态添加Label(Grid grid, int 行, int 列, string 控件name, int 控件宽, int 控件高, string 控件文本)
        {
            System.Windows.Controls.DockPanel dockPanel= null;
            while (grid.RowDefinitions.Count - 1 < 行)
            {
                grid.RowDefinitions.Add(new RowDefinition()); //添加行

            }
            while (grid.ColumnDefinitions.Count - 1 < 列)
            {
                grid.ColumnDefinitions.Add(new ColumnDefinition()); //添加行

            }
    

            //设置绑定到要绑定的控件

            System.Windows.Controls.Label label = new System.Windows.Controls.Label()
            {
                Content = 控件文本,
                Width = 控件宽 / 3 * 2,
                Height = 控件高,
                FontSize = 14,
                Foreground = new System.Windows.Media.SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFBEC9D3")),
                HorizontalContentAlignment = HorizontalAlignment.Center,
                VerticalContentAlignment = VerticalAlignment.Center,
              

            };
            //label.SetBinding(System.Windows.Controls.Label.BackgroundProperty, new Binding("背景颜色"));
            Image image = new Image()
            {


                Width = 40,
                Height = 40,

             
               Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("/fap;component/素材/运动控制页面/红灯.png", UriKind.Relative)),
            };

            image.SetBinding(Image.SourceProperty, new Binding("图像"));

            dockPanel = new DockPanel();
            dockPanel.Children.Add(label);
            dockPanel.Children.Add(image);

            //try
            //{
            //    int k  = (int)Enum.Parse(typeof(枚举.I枚举), 控件name);
            //    image.DataContext = 运动控制数据.I读取结果[k];
            //}
            //catch { }
            //try
            //{
            //    int k = (int)Enum.Parse(typeof(枚举.I枚举), 控件name);
            //    image.DataContext = 运动控制数据.I读取结果[k];
            //}
            //catch { }
            //try
            //{
            //    int k = (int)Enum.Parse(typeof(枚举.报警枚举), 控件name);
            //    image.DataContext = 运动控制数据.报警读取结果[k];
            //}
            //catch { }
            //添加控件 = new System.Windows.Controls.Label(); //创建按钮对象
            grid.RegisterName(控件name, dockPanel); //将block命名block1名称注册到panelOne上

            //添加控件.Name = 控件name; //设置按钮Name属性

            dockPanel.Width = 控件宽; //设置按钮宽度

            dockPanel.Height = 控件高; //设置按钮高度

            //添加控件.Content = dockPanel; //设置按钮文本内容



            grid.Children.Add(dockPanel); //添加到Grid控件

            dockPanel.SetValue(Grid.RowProperty, 行); //设置按钮所在Grid控件的行

            dockPanel.SetValue(Grid.ColumnProperty, 列); //设置按钮所在Grid控件的列



            return dockPanel;

        }
        public static void grid动态添加Label无image(Grid grid, ref System.Windows.Controls.Label 添加控件, int 行, int 列, string 控件name, int 控件宽, int 控件高, string 控件文本)
        {
            while (grid.RowDefinitions.Count - 1 < 行)
            {
                grid.RowDefinitions.Add(new RowDefinition()); //添加行

            }
            while (grid.ColumnDefinitions.Count - 1 < 列)
            {
                grid.ColumnDefinitions.Add(new ColumnDefinition()); //添加行

            }
            System.Windows.Controls.Label label = new System.Windows.Controls.Label()
            {
                //Content = 控件文本,
                Width = 控件宽,
                Height = 控件高,
                FontSize = 10,

                HorizontalContentAlignment = HorizontalAlignment.Center,
                VerticalContentAlignment = VerticalAlignment.Center,
            };


            TextBlock textBlock = new TextBlock()
            {
                TextWrapping = TextWrapping.Wrap,

                FontSize = 10,
                Width = 控件宽 - 30,

                Text = 控件文本,


            };



            添加控件 = label; //创建按钮对象
            添加控件.Content = textBlock;
            grid.RegisterName(控件name, 添加控件); //将block命名block1名称注册到panelOne上

            //添加控件.Name = 控件name; //设置按钮Name属性

            添加控件.Width = 控件宽; //设置按钮宽度

            添加控件.Height = 控件高; //设置按钮高度



            grid.Children.Add(添加控件); //添加到Grid控件

            添加控件.SetValue(Grid.RowProperty, 行); //设置按钮所在Grid控件的行

            添加控件.SetValue(Grid.ColumnProperty, 列); //设置按钮所在Grid控件的列





        }


        public enum 控件类型
        {
            button,
            label,

        }
    }
}



